package com.flydust.apipulse.service;

import com.qiniu.storage.UploadManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.logging.Level;

@Service
public class FileUploadService {
    
    private static final Logger logger = Logger.getLogger(FileUploadService.class.getName());

    @Value("${qiniu.accessKey}")
    private String accessKey;
    
    @Value("${qiniu.secretKey}")
    private String secretKey;
    
    @Value("${qiniu.bucketName}")
    private String bucketName;
    
    @Value("${qiniu.domain}")
    private String domain;

    /**
     * 上传文件到七牛云并返回访问URL
     * @param file 上传的文件
     * @return 文件的访问URL
     * @throws IOException 文件操作异常
     */
    public String uploadFile(MultipartFile file) throws IOException {
        logger.info("开始上传文件到七牛云，文件名: " + file.getOriginalFilename() + ", 大小: " + file.getSize());
        
        try {
            // 验证文件是否为空
            if (file.isEmpty()) {
                logger.warning("上传文件为空");
                throw new IllegalArgumentException("上传文件不能为空");
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + fileExtension;
            
            // 创建七牛云认证
            Auth auth = Auth.create(accessKey, secretKey);
            
            // 配置区域
            Configuration cfg = new Configuration(Region.huadong());
            
            // 生成上传token
            StringMap putPolicy = new StringMap();
            putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\"}");
            long expireSeconds = 3600;
            String upToken = auth.uploadToken(bucketName, null, expireSeconds, putPolicy);
            
            // 创建上传管理器
            UploadManager uploadManager = new UploadManager(cfg);
            
            // 执行上传操作
            uploadManager.put(file.getBytes(), uniqueFilename, upToken);
            
            String fileUrl = domain + "/" + uniqueFilename;
            logger.info("文件上传成功，访问URL: " + fileUrl);
            
            // 返回文件访问URL
            return fileUrl;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "文件上传到七牛云失败", e);
            throw e;
        }
    }
}